#
# Copyright (C) [2024] Xingyun Integrated Circuit, Inc.
#
#   GreenCode was a private technology asset of Xingyun Integrated Circuit， Inc （Confidential）
#   Author :  Shawn.Tan
#   Date : 2025.10.28
#
#   History : Initial Version 2025.10.28
#
#
from base.exception_handlers.ReusableSequence import ReusableSequence
from gpgpu.exception_handlers.ExceptionHandlerContext import RegisterCallRole
from gpgpu.PrivilegeLevel import PrivilegeLevelGPGPU


class InstructionAddressMisalignedHandlerGPGPU(ReusableSequence):
    def __init__(self, aGenThread, aFactory, aStack):
        super().__init__(aGenThread, aFactory, aStack)
        self.privilegeLevel = None

    def generateHandler(self, **kwargs):
        try:
            handler_context = kwargs["handler_context"]
        except KeyError:
            self.error(
                "INTERNAL ERROR: one or more arguments to "
                "InstructionAddressMisalignedHandlerGPGPU generate method "
                "missing."
            )

        self.debug(
            "[InstructionAddressMisalignedHandlerGPGPU] generate handler "
            "address: 0x%x" % self.getPEstate("PC")
        )

        self.privilegeLevel = handler_context.mPrivLevel
        priv_level = PrivilegeLevelGPGPU[self.privilegeLevel]

        stval_reg_index = handler_context.getScratchRegisterIndices(RegisterCallRole.TEMPORARY, 1)

        # retreive misaligned instruction address...

        self.mAssemblyHelper.genReadSystemRegister(
            stval_reg_index, ("%stval" % priv_level.name.lower())
        )

        # mask off low order 2 bits to yield word-aligned address...

        self.mAssemblyHelper.genOrImmediate(stval_reg_index, 0x3)
        self.mAssemblyHelper.genXorImmediate(stval_reg_index, 0x3)

        # write the aligned branch target as the exception return address...

        self.mAssemblyHelper.genWriteSystemRegister(
            ("%sepc" % priv_level.name.lower()), stval_reg_index
        )

        # done.
        self.mAssemblyHelper.genReturn()
